﻿using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web.Mvc;
using System.Collections.Specialized;
using System.Data.SqlClient;
using System.Data;
using NPOI.HSSF.Util;
using System.Security.Cryptography;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.IO.Compression;

namespace DotNet.Utilities.Utils帮助类
{
    public class Utils
    {
        /// <summary>
        /// 通过ClassName获取当前Controller对应的模块实体，ClassName名称不包括"Controller"这个词
        /// </summary>
        /// <param name="className">ClassName名称不包括"Controller"这个词</param>
        /// <returns></returns>
        //public static FrameworkModule GetModuleEntity(string className)
        //{
        //    FrameworkModule fm = null;
        //    using (var dc = new DataAccess.DataContext())
        //    {
        //        fm = dc.FrameworkModules.Where(x => x.ClassName.ToUpper() == className.ToUpper()).SingleOrDefault();
        //    }
        //    return fm;
        //}


        #region 报表导出明细
        /// <summary>
        /// 导出报表明细
        /// </summary>
        /// <param name="dataTable"></param>
        /// <param name="sheetName"></param>
        /// <returns></returns>
        public static byte[] ExcelByteGet(DataTable dataTable)
        {

            //准备好sheet，每6万行生成一个sheet
            int sheetno = ((dataTable.Rows.Count - 1) / 60000) + 1;
            HSSFWorkbook workbook = new HSSFWorkbook();
            List<HSSFSheet> sheets = new List<NPOI.HSSF.UserModel.HSSFSheet>();

            var headerStyle = workbook.CreateCellStyle();
            ////设定单元格边框
            //headerStyle.BorderBottom = BorderStyle.THIN;
            //headerStyle.BorderLeft = BorderStyle.THIN;
            //headerStyle.BorderRight = BorderStyle.THIN;
            //headerStyle.BorderTop = BorderStyle.THIN;
            //用灰色填充背景
            var headerbg = HSSFColor.GREY_25_PERCENT.index;
            headerStyle.FillForegroundColor = headerbg;
            headerStyle.FillPattern = FillPatternType.SOLID_FOREGROUND;
            headerStyle.FillBackgroundColor = headerbg;

            //循环生成所有sheet，并为每个sheet添加表头
            for (int i = 1; i <= sheetno; i++)
            {
                HSSFSheet sheet = workbook.CreateSheet("Sheet" + i) as HSSFSheet;
                HSSFRow dataRow = sheet.CreateRow(0) as HSSFRow;
                //生成表头
                MakeExcelHeader(dataTable, dataRow, headerStyle);
                sheets.Add(sheet);
            }

            //循环填写数据
            int rowIndex = 1;
            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                int sheetindex = ((rowIndex - 1) / 60000);
                HSSFRow dateRow = sheets[sheetindex].CreateRow(rowIndex - sheetindex * 60000) as HSSFRow;
                for (int j = 1; j < dataTable.Columns.Count; j++)
                {
                    double res = 0.00000;
                    bool flag = double.TryParse(Convert.ToString(dataTable.Rows[i][j]), out res);
                    if (flag)
                    {
                        res = Convert.ToDouble(dataTable.Rows[i][j]);
                        dateRow.CreateCell(j - 1).SetCellValue(res);
                    }
                    else
                    {
                        dateRow.CreateCell(j - 1).SetCellValue(Convert.ToString(dataTable.Rows[i][j]));
                    }
                }
                rowIndex++;
            }

            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                ms.Flush();
                ms.Position = 0;
                return ms.ToArray();
            }

        }

        private static void MakeExcelHeader(DataTable dataTable, HSSFRow dataRow, ICellStyle headerStyle)
        {
            //列头：
            List<string> headerCols = new List<string>();
            for (int i = 1; i < dataTable.Columns.Count; i++)
            {
                headerCols.Add(Convert.ToString(dataTable.Columns[i].ColumnName));
            }

            //设置表头
            SetHeaderValue(dataRow, headerCols);
        }

        private static void SetHeaderValue(HSSFRow row, List<string> headers)
        {
            if (headers.Count > 0)
            {
                int i = 0;
                foreach (var s in headers)
                {
                    row.CreateCell(i).SetCellValue(headers[i]);
                    i++;
                }
            }
        }
        #endregion 报表导出明细

        #region 返回手动生成结算单错误消息 by sc
        /// <summary>
        /// 返回手动生成结算单错误消息 by sc
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        public static string ReturnErrorMsg(int result)
        {
            string errorMsg = string.Empty;
            switch (result)
            {
                case 1:
                    errorMsg = "其他用户正在生成结算单，暂时无法操作!";
                    break;
                case 2:
                    errorMsg = "有未分组的仓库,无法生成结算单";
                    break;
                case 3:
                    errorMsg = "所选记录不属于同一结算商，无法生成结算单";
                    break;
                case 4:
                    errorMsg = "所选记录不属于同一法人，无法生成结算单";
                    break;
            }
            return errorMsg;
        }
        #endregion

        //#region 税后金额计算通用方法
        ///// <summary>
        ///// 其他调账税后金额
        ///// </summary>
        ///// <param name="dc">dc</param>
        ///// <param name="storageID">仓库ID</param>
        ///// <param name="logicProviderID">物流商ID</param>
        ///// <param name="category">类别（运输/仓储 1/2）</param>
        ///// <param name="amount">金额</param>
        ///// <returns>税后金额</returns>
        //public static decimal? AftertaxAmountGet(DataAccess.DataContext dc, long feeTypeID, long logicProviderID, decimal? amount)
        //{
        //    decimal? afterTaxAmount;
        //    var taxRate = dc.TaxRates.Where(x => x.LogisticProviderID == logicProviderID && x.FeeTypeID == feeTypeID).FirstOrDefault();
        //    if (taxRate != null)
        //    {
        //        if ((int)taxRate.OperatType == 1) //乘以
        //        {
        //            afterTaxAmount = amount.Value * (1 - taxRate.Rate);
        //        }
        //        else
        //        {
        //            afterTaxAmount = amount.Value / (1 + taxRate.Rate);
        //        }
        //    }
        //    else
        //    {
        //        afterTaxAmount = amount;
        //    }
        //    return afterTaxAmount;
        //}

        //#endregion

        #region 属性、字段、值相关方法
        public static string GetPropertyName(Expression expression, bool getAll = true)
        {
            if (expression == null)
            {
                return "";
            }
            MemberExpression me = null;
            LambdaExpression le = null;
            if (expression is MemberExpression)
            {
                me = expression as MemberExpression;
            }
            if (expression is LambdaExpression)
            {
                le = expression as LambdaExpression;
                if (le.Body is MemberExpression)
                {
                    me = le.Body as MemberExpression;
                }
                if (le.Body is UnaryExpression)
                {
                    me = (le.Body as UnaryExpression).Operand as MemberExpression;
                }
            }
            string rv = "";
            if (me != null)
            {
                rv = me.Member.Name;
            }
            while (me != null && getAll && me.NodeType == ExpressionType.MemberAccess)
            {
                Expression exp = me.Expression;
                if (exp is MemberExpression)
                {
                    rv = (exp as MemberExpression).Member.Name + "." + rv;
                    me = exp as MemberExpression;
                }
                else if (exp is MethodCallExpression)
                {
                    var mexp = exp as MethodCallExpression;
                    if (mexp.Method.Name == "get_Item")
                    {
                        var obj = ((mexp.Arguments[0] as MemberExpression).Expression as ConstantExpression).Value;
                        var index = obj.GetType().GetField((mexp.Arguments[0] as MemberExpression).Member.Name).GetValue(obj);
                        rv = (mexp.Object as MemberExpression).Member.Name + "[" + index + "]." + rv;
                        me = mexp.Object as MemberExpression;
                    }
                }
                else
                {
                    break;
                }
            }
            return rv;
        }

        public static string GetPropertyDisplayName(PropertyInfo pi, string fixedString = null)
        {
            if (!string.IsNullOrEmpty(fixedString))
            {
                return Utils.GetResourceText(fixedString);
            }
            if (fixedString == "")
            {
                return "";
            }
            string rv = "";
            var dis = pi.GetCustomAttributes(typeof(DisplayAttribute), false).FirstOrDefault() as DisplayAttribute;
            if (dis != null && !string.IsNullOrEmpty(dis.Name))
            {
                if (dis.ResourceType == null)
                {
                    rv = dis.Name;
                }
                else
                {
                    rv = Utils.GetResourceText(dis.Name);
                }
            }
            else
            {
                rv = pi.Name;
            }
            return rv;
        }

        public static string GetPropertyDisplayName(Expression expression, string fixedString = null)
        {
            return Utils.GetPropertyDisplayName(Utils.GetPropertyInfo(expression), fixedString);
        }

        public static PropertyInfo GetPropertyInfo(Expression expression)
        {
            MemberExpression me = null;
            LambdaExpression le = null;
            if (expression is MemberExpression)
            {
                me = expression as MemberExpression;
            }
            if (expression is LambdaExpression)
            {
                le = expression as LambdaExpression;
                if (le.Body is MemberExpression)
                {
                    me = le.Body as MemberExpression;
                }
                if (le.Body is UnaryExpression)
                {
                    me = (le.Body as UnaryExpression).Operand as MemberExpression;
                }
            }
            PropertyInfo rv = null;
            if (me != null)
            {
                rv = me.Member.DeclaringType.GetProperty(me.Member.Name);
            }
            return rv;
        }

        public static string GetPropertyValue(LambdaExpression exp, object obj)
        {
            //获取表达式的值，并过滤单引号
            var expValue = exp.Compile().DynamicInvoke(obj);
            string val = "";
            if (expValue != null)
            {
                val = expValue.ToString().Replace("'", "\\\'").Replace(Environment.NewLine, "\\n").Replace("\n", "\\n");
            }
            return val;
        }

        public static string GetPropertyErrors<T>(HtmlHelper<T> html, Expression exp)
        {
            var expName = Utils.GetPropertyName(exp);
            return GetPropertyErrors(html, expName);
        }

        public static string GetPropertyErrors<T>(HtmlHelper<T> html, string property)
        {
            string expError = "";
            //获取表达式相关的错误信息
            if (html.ViewData.ModelState[property] != null)
            {
                var errors = html.ViewData.ModelState[property].Errors;
                if (errors != null && errors.Count > 0)
                {
                    expError = "[" + errors.ToSpratedString(x => x, (x) => { return "'" + (x.ErrorMessage == "" ? x.Exception.Message : x.ErrorMessage).Replace("'", "\\\'") + "'"; }) + "]";
                }
            }
            return expError;
        }

        public static bool IsPropertyRequired(PropertyInfo pi)
        {
            bool isRequired = false;
            //如果需要显示星号，则判断是否是必填项，如果是必填则在内容后面加上星号
            //所有int，float。。。这种Primitive类型的，肯定都是必填
            if (pi.PropertyType.IsPrimitive || pi.PropertyType.IsEnum)
            {
                isRequired = true;
            }
            else
            {
                //对于其他类，检查是否有RequiredAttribute，如果有就是必填
                var required = pi.GetCustomAttributes(typeof(RequiredAttribute), false).FirstOrDefault() as RequiredAttribute;
                if (required != null && required.AllowEmptyStrings == false)
                {
                    isRequired = true;
                }
                else
                {
                    //如果没有RequiredAttribute，检查是否有自定义的MLRequiredAttribute,如果有就是必填
                    var mlrequired = pi.GetCustomAttributes(typeof(MLRequiredAttribute), false).FirstOrDefault() as MLRequiredAttribute;
                    if (mlrequired != null)
                    {
                        isRequired = true;
                    }
                }
            }
            return isRequired;
        }

        public static void SetPropertyValue(object source, string property, object value, string prefix = null, bool stringBasedValue = false)
        {
            try
            {
                List<string> level = new List<string>();
                if (property.Contains('.'))
                {
                    level.AddRange(property.Split('.'));
                }
                else
                {
                    level.Add(property);
                }

                if (!string.IsNullOrWhiteSpace(prefix))
                {
                    level.Insert(0, prefix);
                }
                object temp = source;
                Type tempType = source.GetType();
                for (int i = 0; i < level.Count - 1; i++)
                {
                    var pro = tempType.GetProperty(level[i]);
                    if (pro != null)
                    {
                        var va = pro.GetValue(temp, null);
                        if (va != null)
                        {
                            temp = va;
                        }
                        else
                        {
                            var newInstance = va.GetType().GetConstructor(Type.EmptyTypes).Invoke(null);
                            pro.SetValue(temp, newInstance, null);
                            temp = newInstance;
                        }
                        tempType = pro.PropertyType;
                    }
                }

                var fproperty = tempType.GetProperty(level.Last());
                if (fproperty == null)
                {
                    return;
                }
                if (value == null)
                {
                    fproperty.SetValue(temp, value, null);
                }

                bool isArray = false;
                if (value != null && value.GetType().IsArray == true)
                {
                    isArray = true;
                }

                if (stringBasedValue == true)
                {
                    Type propertyType = fproperty.PropertyType;
                    if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(List<>))
                    {
                        var list = propertyType.GetConstructor(Type.EmptyTypes).Invoke(null) as IList;

                        var gs = propertyType.GenericTypeArguments;
                        try
                        {
                            if (isArray)
                            {
                                var a = (value as object[]);
                                for (int i = 0; i < a.Length; i++)
                                {
                                    list.Add(ConvertValue(a[i], gs[0]));
                                }
                            }
                        }
                        catch { }
                        fproperty.SetValue(temp, list, null);
                    }
                    else
                    {
                        if (isArray)
                        {
                            var a = (value as object[]);
                            if (a.Length == 1)
                            {
                                value = a[0];
                            }
                        }

                        object val = ConvertValue(value, fproperty.PropertyType);
                        fproperty.SetValue(temp, val, null);
                    }
                }
                else
                {
                    fproperty.SetValue(temp, value, null);
                }
            }
            catch { }
        }

        private static object ConvertValue(object value, Type propertyType)
        {
            object val = null;
            if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                var gs = propertyType.GenericTypeArguments;
                try
                {
                    val = ConvertValue(value, gs[0]);
                }
                catch { }
            }
            else if (propertyType.IsEnum)
            {
                val = Enum.Parse(propertyType, value.ToString());
            }
            else if (propertyType == typeof(string))
            {
                val = value == null ? null : value.ToString().Trim();
            }
            else if (propertyType == typeof(Guid))
            {
                Guid g = Guid.Empty;
                Guid.TryParse(value.ToString(), out g);
                val = g;
            }
            else
            {
                try
                {
                    if (value.ToString().StartsWith("`") && value.ToString().EndsWith("`"))
                    {
                        string inner = value.ToString().Trim('`').TrimEnd(',');
                        if (!string.IsNullOrWhiteSpace(inner))
                        {
                            val = propertyType.GetConstructor(Type.EmptyTypes).Invoke(null);
                            string[] pair = inner.Split(',');
                            var gs = propertyType.GetGenericArguments();
                            foreach (var p in pair)
                            {
                                (val as IList).Add(Convert.ChangeType(p, gs[0]));
                            }
                        }
                    }
                    else
                    {
                        val = Convert.ChangeType(value.ToString(), propertyType);
                    }
                }
                catch
                {
                }
            }
            return val;
        }
        #endregion 属性、字段、值相关方法

        #region 取得当前设置的语言环境
        public static SupportedLanguage GetCurrentLanguage()
        {
            var cul = System.Threading.Thread.CurrentThread.CurrentUICulture;
            return null;
            //return BaseController.Languages.Where(x => x.LanguageCode.ToLower() == cul.Name.ToLower() || x.LanguageCode.ToLower() == cul.TwoLetterISOLanguageName.ToLower()).SingleOrDefault();
        }
        #endregion

        #region 取得语言环境下的标点
        public static string GetCurrentComma()
        {
            if (GetCurrentLanguage().LanguageCode == "zh-cn")
            {
                return "：";
            }
            else
            {
                return ":";
            }
        }
        #endregion

        #region 根据名称取得ID
        public static string GetIDByName(string fieldName)
        {
            return fieldName == null ? "" : fieldName.Replace(".", "_").Replace("[", "_").Replace("]", "_");
        }
        #endregion

        #region 对比新旧lsitbox，返回要移除的和要添加的
        public static void CheckDifference<T>(List<T> oldList, List<T> newList, out List<T> ToRemove, out List<T> ToAdd) where T : BasePoco
        {
            ToRemove = new List<T>();
            ToAdd = new List<T>();
            foreach (var oldItem in oldList)
            {
                bool exist = false;
                foreach (var newItem in newList)
                {
                    if (oldItem.ID == newItem.ID)
                    {
                        exist = true;
                        break;
                    }
                }
                if (exist == false)
                {
                    ToRemove.Add(oldItem);
                }
            }
            foreach (var newItem in newList)
            {
                bool exist = false;
                foreach (var oldItem in oldList)
                {
                    if (newItem.ID == oldItem.ID)
                    {
                        exist = true;
                        break;
                    }
                }
                if (exist == false)
                {
                    ToAdd.Add(newItem);
                }
            }
        }
        #endregion

        #region 取得excel颜色
        public static short GetExcelColor(System.Drawing.Color color)
        {
            var colors = typeof(HSSFColor).GetNestedTypes().ToList();
            foreach (var col in colors)
            {
                var pro = col.GetField("hexString");
                if (pro == null)
                {
                    continue;
                }
                var hex = pro.GetValue(null);
                var rgb = hex.ToString().Split(':');
                for (int i = 0; i < rgb.Length; i++)
                {
                    if (rgb[i].Length > 2)
                    {
                        rgb[i] = rgb[i].Substring(0, 2);
                    }
                }
                int r = Convert.ToInt16(rgb[0], 16);
                int g = Convert.ToInt16(rgb[1], 16);
                int b = Convert.ToInt16(rgb[2], 16);
                if (r == color.R && g == color.G && b == color.B)
                {
                    return (short)col.GetField("index").GetValue(null);
                }
            }
            return HSSFColor.COLOR_NORMAL;
        }
        #endregion

        #region 生成下拉
        public static List<SelectListItem> GetBoolCombo(BoolComboTypes boolType, DotNet.Utilities.EnumToSelectHelper.ComboFirstRow firstRow, bool? defaultValue = null, string trueText = null, string falseText = null, string selectText = null)
        {
            List<SelectListItem> rv = new List<SelectListItem>();
            if (firstRow != DotNet.Utilities.EnumToSelectHelper.ComboFirstRow.无)
            {
                SelectListItem select = new SelectListItem();
                if (firstRow == DotNet.Utilities.EnumToSelectHelper.ComboFirstRow.请选择)
                {
                    select.Text = "请选择";
                }
                if (firstRow == DotNet.Utilities.EnumToSelectHelper.ComboFirstRow.全部)
                {
                    select.Text = "全部";
                }
                if (firstRow == DotNet.Utilities.EnumToSelectHelper.ComboFirstRow.自定义)
                {
                    select.Text = selectText == null ? "" : selectText;
                }
                select.Value = null;
                if (defaultValue == null)
                {
                    select.Selected = true;
                }
                rv.Add(select);
            }
            string yesText = "";
            string noText = "";
            switch (boolType)
            {
                case BoolComboTypes.是否:
                    yesText = "是";
                    noText = "否";
                    break;
                case BoolComboTypes.有效无效:
                    yesText = "有效";
                    noText = "无效";
                    break;
                case BoolComboTypes.男女:
                    yesText = "男";
                    noText = "女";
                    break;
                case BoolComboTypes.有无:
                    yesText = "有";
                    noText = "无";
                    break;
                case BoolComboTypes.自定义:
                    yesText = trueText == null ? "" : trueText;
                    noText = falseText == null ? "" : falseText;
                    break;
                default:
                    break;
            }
            SelectListItem yesItem = new SelectListItem();
            yesItem.Text = yesText;
            yesItem.Value = "true";
            if (defaultValue == true)
            {
                yesItem.Selected = true;
            }
            SelectListItem noItem = new SelectListItem();
            noItem.Text = noText;
            noItem.Value = "false";
            if (defaultValue == false)
            {
                noItem.Selected = true;
            }
            rv.Add(yesItem);
            rv.Add(noItem);
            return rv;
        }
        #endregion

        #region  根据所有项目和已选项目生成已选项目数组，并从所有项目中把已选项目移除
        /// <summary>
        /// 根据所有项目和已选项目ID生成已选项目数组，并从所有项目中把已选项目移除
        /// </summary>
        /// <param name="allItems">所有项目</param>
        /// <param name="selectedItems">已选项目</param>
        /// <param name="selectedIds">已选ID</param>
        public static void MakeSelectedItem(List<SelectListItem> allItems, List<SelectListItem> selectedItems, List<long> selectedIds)
        {
            if (selectedIds == null)
            {
                selectedIds = new List<long>();
            }
            List<string> toString = new List<string>();
            selectedIds.ForEach(x => toString.Add(x.ToString()));
            selectedItems.AddRange(allItems.Where(x => toString.Contains(x.Value)).ToList());
            selectedItems.ForEach(x => allItems.Remove(x));
        }

        public static void MakeSelectedItem(List<SelectListItem> allItems, List<SelectListItem> selectedItems, List<long?> selectedIds)
        {
            if (selectedIds == null)
            {
                selectedIds = new List<long?>();
            }
            List<string> toString = new List<string>();
            selectedIds.ForEach(x => toString.Add(x.ToString()));
            selectedItems.AddRange(allItems.Where(x => toString.Contains(x.Value)).ToList());
            selectedItems.ForEach(x => allItems.Remove(x));
        }

        public static void MakeSelectedItem(List<SelectListItem> allItems, List<SelectListItem> selectedItems, List<string> selectedIds)
        {
            if (selectedIds == null)
            {
                selectedIds = new List<string>();
            }
            List<string> toString = new List<string>();
            selectedIds.ForEach(x => toString.Add(x.ToString()));
            selectedItems.AddRange(allItems.Where(x => toString.Contains(x.Value)).ToList());
            selectedItems.ForEach(x => allItems.Remove(x));
        }
        #endregion

        //#region 根据Controller生成模块
        //public static List<FrameworkModule> GetAllControllerModules()
        //{
        //    List<FrameworkModule> rv = new List<FrameworkModule>();
        //    //获取当前执行的dll中包含的所有类
        //    var types = Assembly.GetExecutingAssembly().GetTypes();
        //    //循环所有类
        //    foreach (var item in types)
        //    {
        //        //如果是controller
        //        if (item.BaseType == typeof(BaseController))
        //        {
        //            object[] pubattr = item.GetCustomAttributes(typeof(PublicAttribute), false);
        //            object[] arattr = item.GetCustomAttributes(typeof(AllRightsAttribute), false);
        //            if (pubattr.Length > 0 || arattr.Length > 0)
        //            {
        //                continue;
        //            }
        //            FrameworkModule model = new FrameworkModule();
        //            model.MLContents = new List<FrameworkModuleMLContent>();
        //            model.ClassName = item.Name.Replace("Controller", "");
        //            model.NameSpace = item.Namespace;
        //            //获取controller上标记的ActionDescription属性的值
        //            object[] attrs = item.GetCustomAttributes(typeof(ActionDescriptionAttribute), false);
        //            if (attrs.Length > 0)
        //            {
        //                string nameKey = (attrs[0] as ActionDescriptionAttribute).Description;
        //                foreach (var lan in BaseController.Languages)
        //                {
        //                    model.MLContents.Add(new FrameworkModuleMLContent { LanguageCode = lan.LanguageCode, ModuleName = GetResourceText(nameKey, lan) });
        //                }
        //            }
        //            else
        //            {
        //                foreach (var lan in BaseController.Languages)
        //                {
        //                    model.MLContents.Add(new FrameworkModuleMLContent { LanguageCode = lan.LanguageCode, ModuleName = model.ClassName });
        //                }
        //            }
        //            //获取该controller下所有的方法
        //            var methods = item.GetMethods(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance);
        //            //过滤掉特殊方法
        //            methods = methods.Where(x => x.IsSpecialName == false).ToArray();
        //            model.Actions = new List<FrameworkAction>();
        //            //循环所有方法
        //            foreach (var method in methods)
        //            {
        //                object[] pubattr2 = method.GetCustomAttributes(typeof(PublicAttribute), false);
        //                object[] arattr2 = method.GetCustomAttributes(typeof(AllRightsAttribute), false);
        //                if (pubattr2.Length > 0 || arattr2.Length > 0)
        //                {
        //                    continue;
        //                }
        //                object[] postAttr = method.GetCustomAttributes(typeof(HttpPostAttribute), false);
        //                //如果不是post的方法，则添加到controller的action列表里
        //                if (postAttr.Length == 0)
        //                {
        //                    FrameworkAction action = new FrameworkAction();
        //                    action.Module = model;
        //                    action.MLContents = new List<FrameworkActionMLContent>();
        //                    action.MethodName = method.Name;
        //                    object[] attrs2 = method.GetCustomAttributes(typeof(ActionDescriptionAttribute), false);
        //                    if (attrs2.Length > 0)
        //                    {
        //                        string nameKey = (attrs2[0] as ActionDescriptionAttribute).Description;
        //                        foreach (var lan in BaseController.Languages)
        //                        {
        //                            action.MLContents.Add(new FrameworkActionMLContent { LanguageCode = lan.LanguageCode, ActionName = GetResourceText(nameKey, lan) });
        //                        }
        //                    }
        //                    else
        //                    {
        //                        foreach (var lan in BaseController.Languages)
        //                        {
        //                            action.MLContents.Add(new FrameworkActionMLContent { LanguageCode = lan.LanguageCode, ActionName = action.MethodName });
        //                        }
        //                    }
        //                    var pars = method.GetParameters();
        //                    if (pars != null && pars.Length > 0)
        //                    {
        //                        action.ParasToRunTest = new List<string>();
        //                        foreach (var par in pars)
        //                        {
        //                            action.ParasToRunTest.Add(par.Name);
        //                        }
        //                    }
        //                    model.Actions.Add(action);
        //                }
        //            }
        //            //再次循环所有方法
        //            foreach (var method in methods)
        //            {
        //                object[] pubattr2 = method.GetCustomAttributes(typeof(PublicAttribute), false);
        //                object[] arattr2 = method.GetCustomAttributes(typeof(AllRightsAttribute), false);
        //                if (pubattr2.Length > 0 || arattr2.Length > 0)
        //                {
        //                    continue;
        //                }
        //                object[] postAttr = method.GetCustomAttributes(typeof(HttpPostAttribute), false);
        //                //找到post的方法且没有同名的非post的方法，添加到controller的action列表里
        //                if (postAttr.Length > 0 && model.Actions.Where(x => x.MethodName.ToLower() == method.Name.ToLower()).FirstOrDefault() == null)
        //                {
        //                    FrameworkAction action = new FrameworkAction();
        //                    action.Module = model;
        //                    action.MLContents = new List<FrameworkActionMLContent>();
        //                    action.MethodName = method.Name;
        //                    object[] attrs2 = method.GetCustomAttributes(typeof(ActionDescriptionAttribute), false);
        //                    if (attrs2.Length > 0)
        //                    {
        //                        string nameKey = (attrs2[0] as ActionDescriptionAttribute).Description;
        //                        foreach (var lan in BaseController.Languages)
        //                        {
        //                            action.MLContents.Add(new FrameworkActionMLContent { LanguageCode = lan.LanguageCode, ActionName = Utils.GetResourceText(nameKey, lan) });
        //                        }
        //                    }
        //                    else
        //                    {
        //                        foreach (var lan in BaseController.Languages)
        //                        {
        //                            action.MLContents.Add(new FrameworkActionMLContent { LanguageCode = lan.LanguageCode, ActionName = action.MethodName });
        //                        }
        //                    }
        //                    model.Actions.Add(action);
        //                }
        //            }
        //            rv.Add(model);
        //        }
        //    }
        //    return rv;
        //}
        //#endregion

        //#region 取得可访问URL列表
        //public static List<string> GetAllAccessUrls()
        //{
        //    List<string> rv = new List<string>();
        //    //获取当前执行的dll中包含的所有类
        //    var types = Assembly.GetExecutingAssembly().GetTypes();
        //    //循环所有类
        //    foreach (var item in types)
        //    {
        //        //如果是controller
        //        if (item.BaseType == typeof(BaseController))
        //        {
        //            string ControllerName = item.Name.Replace("Controller", "");
        //            bool includeAll = false;
        //            //获取controller上标记的ActionDescription属性的值
        //            object[] attrs = item.GetCustomAttributes(typeof(AllRightsAttribute), false);
        //            object[] attrs2 = item.GetCustomAttributes(typeof(PublicAttribute), false);
        //            if (attrs.Length > 0 || attrs2.Length > 0)
        //            {
        //                includeAll = true;
        //            }

        //            //获取该controller下所有的方法
        //            var methods = item.GetMethods(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance);
        //            //过滤掉特殊方法
        //            methods = methods.Where(x => x.IsSpecialName == false).ToArray();
        //            string ActionName = "";
        //            //循环所有方法
        //            foreach (var method in methods)
        //            {
        //                object[] postAttr = method.GetCustomAttributes(typeof(HttpPostAttribute), false);
        //                //如果不是post的方法，则添加到controller的action列表里
        //                if (postAttr.Length == 0)
        //                {
        //                    ActionName = method.Name;
        //                    if (includeAll == true)
        //                    {
        //                        rv.Add(ControllerName + "/" + ActionName);
        //                    }
        //                    else
        //                    {
        //                        object[] attrs3 = method.GetCustomAttributes(typeof(AllRightsAttribute), false);
        //                        object[] attrs4 = method.GetCustomAttributes(typeof(PublicAttribute), false);
        //                        if (attrs3.Length > 0 || attrs4.Length > 0)
        //                        {
        //                            rv.Add(ControllerName + "/" + ActionName);
        //                        }
        //                    }
        //                }
        //            }
        //            //再次循环所有方法
        //            foreach (var method in methods)
        //            {
        //                object[] postAttr = method.GetCustomAttributes(typeof(HttpPostAttribute), false);
        //                //找到post的方法且没有同名的非post的方法，添加到controller的action列表里
        //                if (postAttr.Length > 0 && !rv.Contains(ControllerName + "/" + method.Name))
        //                {
        //                    ActionName = method.Name;
        //                    if (includeAll == true)
        //                    {
        //                        rv.Add(ControllerName + "/" + ActionName);
        //                    }
        //                    else
        //                    {
        //                        object[] attrs5 = method.GetCustomAttributes(typeof(AllRightsAttribute), false);
        //                        object[] attrs6 = method.GetCustomAttributes(typeof(PublicAttribute), false);
        //                        if (attrs5.Length > 0 || attrs6.Length > 0)
        //                        {
        //                            rv.Add(ControllerName + "/" + ActionName);
        //                        }
        //                    }
        //                }
        //            }
        //        }
        //    }
        //    return rv;
        //}
        //#endregion

        #region Zip解压缩
        public static string ZipAndBase64Encode(string input)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(input);
            MemoryStream inputms = new MemoryStream(buffer);
            MemoryStream outputms = new MemoryStream();
            using (GZipStream zip = new GZipStream(outputms, CompressionMode.Compress))
            {
                inputms.CopyTo(zip);
            }
            byte[] rv = outputms.ToArray();
            inputms.Close();
            return Convert.ToBase64String(rv);
        }

        public static string UnZipAndBase64Decode(string input)
        {
            byte[] inputstr = Convert.FromBase64String(input);
            MemoryStream inputms = new MemoryStream(inputstr);
            MemoryStream outputms = new MemoryStream();
            using (GZipStream zip = new GZipStream(inputms, CompressionMode.Decompress))
            {
                zip.CopyTo(outputms);
            }
            byte[] rv = outputms.ToArray();
            outputms.Close();
            return Encoding.UTF8.GetString(rv);
        }
        #endregion

        #region EncodeScriptJson
        public static string EncodeScriptJson(string input)
        {
            if (input == null)
            {
                return "";
            }
            else
            {
                return input.Replace(Environment.NewLine, "").Replace("\"", "\\\\\\\"").Replace("'", "\\'");
            }
        }
        #endregion

        #region 取得框架版本号
        public static string GetFrameworkVersion()
        {
            System.Reflection.Assembly asm = System.Reflection.Assembly.GetExecutingAssembly();
            return asm.GetName().Version.ToString();
        }
        #endregion

        #region 取得资源文件
        public static string GetResourceText(string key, SupportedLanguage lan = null)
        {
            if (string.IsNullOrEmpty(key))
            {
                return "";
            }
            if (lan == null)
            {
                lan = GetCurrentLanguage();
            }
            CultureInfo ci = CultureInfo.GetCultureInfoByIetfLanguageTag(lan.LanguageCode);
            //string name = Resources.Language.ResourceManager.GetString(key, ci);
            string name = "123";
            return string.IsNullOrWhiteSpace(name) ? key : name;
        }
        #endregion

        #region 删除文件
        public static void DeleteFile(string path)
        {
            try
            {
                System.IO.File.Delete(path);
            }
            catch { }
        }
        #endregion

        #region 返回审批状态
        public static string GetWorkFlowStatus(string status)
        {
            string rv = "";
            if (status == "0")
            {
                rv = "未审批";
            }
            if (status == "1")
            {
                rv = "通过";
            }
            if (status == "2")
            {
                rv = "拒绝";
            }
            if (status == "3")
            {
                rv = "审批中";
            }
            return rv;
        }
        #endregion

        #region  根据枚举返回SelectListItem列表  add by dufei （暂时无用）
        //public static  List<SelectListItem> GetSelectListItemsByEnum<T>(ComboFirstRow firstRow = ComboFirstRow.请选择,string selectItem=null)
        //{
        //    List<SelectListItem> rv = new List<SelectListItem>();

        //    Type enumType = typeof(T); // 创建类型
        //    FieldInfo[] enumFields = enumType.GetFields(); //获取字段信息对象集合

        //    foreach (var field in enumFields)
        //    {
        //        if (!field.IsSpecialName)
        //        {
        //            rv.Add(new SelectListItem() { Text = field.Name, Value = field.GetRawConstantValue().ToString() });
        //        }
        //    }

        //    switch (firstRow)
        //    {
        //        case ComboFirstRow.无:
        //            break;
        //        case ComboFirstRow.请选择:
        //            rv.Insert(0, new SelectListItem { Text = Resources.Language.请选择, Value = "" });
        //            break;
        //        case ComboFirstRow.全部:
        //            rv.Insert(0, new SelectListItem { Text = Resources.Language.全部, Value = "" });
        //            break;
        //        default:
        //            break;
        //    }

        //    if (selectItem != null)
        //    {
        //        rv.Where(x => x.Text == selectItem).FirstOrDefault().Selected = true;
        //    }

        //    return rv;
        //}
        #endregion

        #region 取得枚举描述信息(暂时无用)
        /// <summary>
        /// 取得枚举描述信息
        /// </summary>
        /// <typeparam name="T">枚举</typeparam>
        /// <param name="enumValue">枚举值</param>
        /// <returns></returns>
        public static string GetEnumText<T>(int enumValue)
        {
            string result = string.Empty;
            Type enumType = typeof(T); // 创建类型
            FieldInfo[] enumFields = enumType.GetFields(); //获取字段信息对象集合

            foreach (var field in enumFields)
            {
                if (!field.IsSpecialName)
                {
                    if (Convert.ToInt32(field.GetRawConstantValue()) == enumValue)
                    {
                        result = field.Name;
                        break;
                    }
                }
            }
            return result;
        }
        #endregion

        #region 生成单号 add by dufei
        /// <summary>
        /// 生成单号（前缀+年月日+流水号，例如：YSJS20130708001）
        /// </summary>
        /// <param name="type">模块枚举，如有需要，自行在Utils文件中添加</param>
        /// <param name="Prefix">单号前缀</param>
        /// <param name="length">流水号位数，默认3位</param>
        /// <returns></returns>
        public static string GetBillNo(BillTypeEnum type, string Prefix = null, int length = 3)
        {
            if (Prefix == null)
            {
                Prefix = type.ToString();
            }
            return Prefix + DateTime.Now.ToString("yyyyMMdd") + GetSeed(type, length);

        }
        #endregion

        #region 生成拍位号 jiankang
        /// <summary>
        /// 生成单号（PL（2）+RDC（4）+年月日（5）+流水号（4），例如：YSJS20130708001）
        /// </summary>
        /// <param name="type">模块枚举，如有需要，自行在Utils文件中添加</param>
        /// <param name="Prefix">单号前缀</param>
        /// <param name="length">流水号位数，默认3位</param>
        /// <returns></returns>
        public static string GetPalletNo(string type, string Prefix = null, int length = 4)
        {
            return DateTime.Now.ToString("yyyyMMdd").Substring(3, 5) + GetSeed(type, length, true);
        }
        #endregion

        #region 生成经销商编码 jiankang
        /// <summary>
        /// 四位流水号
        /// </summary>
        /// <param name="type">模块枚举，如有需要，自行在Utils文件中添加</param>
        /// <param name="Prefix">单号前缀</param>
        /// <param name="length">流水号位数，默认3位</param>
        /// <returns></returns>
        public static string GetAgencyCode(string type, string Prefix = null, int length = 4)
        {
            return GetSeed(type, length, false);
        }
        #endregion

        #region 生成单号 add by lizhenga
        /// <summary>
        /// 生成单号（前缀+流水号）     
        /// <returns></returns>
        public static string GetBillNoWithnotDate(BillTypeEnum type, string Prefix = null, int length = 3)
        {
            if (Prefix == null)
            {
                Prefix = type.ToString();
            }
            return Prefix + GetSeed(type, length, false);

        }
        #endregion

        #region 取得单号种子 add by dufei
        public static string GetSeed(BillTypeEnum type, int length = 3, bool isNeedDate = true)
        {
            //using (var dc = new  DataContext())
            //{
                string code = "";

                SqlParameter paramOut = new SqlParameter("@No", SqlDbType.NVarChar, length);
                paramOut.Direction = ParameterDirection.Output;
                var parms = new SqlParameter[] 
                { 
                    new SqlParameter("@Module", type.ToString()), 
                    new SqlParameter("@Length", length), 
                    new SqlParameter("@IsNeedDate", isNeedDate), 
                    paramOut 
                };
                //dc.RunSP("SP_Base_GetSeed", parms);
                if (paramOut.Value != null)
                {
                    code = paramOut.Value.ToString();
                }

                if (string.IsNullOrEmpty(code))
                {
                    throw new Exception("<" + type + ">" + "无法找到种子");
                }
                return code;
           // }
        }

        public static string GetSeed(string type, int length = 3, bool isNeedDate = true)
        {
            //using (var dc = new DataContext())
            //{
                string code = "";

                SqlParameter paramOut = new SqlParameter("@No", SqlDbType.NVarChar, length);
                paramOut.Direction = ParameterDirection.Output;
                var parms = new SqlParameter[] 
                { 
                    new SqlParameter("@Module", type.ToString()), 
                    new SqlParameter("@Length", length), 
                    new SqlParameter("@IsNeedDate", isNeedDate), 
                    paramOut 
                };
                //dc.RunSP("SP_Base_GetSeed", parms);
                if (paramOut.Value != null)
                {
                    code = paramOut.Value.ToString();
                }

                if (string.IsNullOrEmpty(code))
                {
                    throw new Exception("<" + type + ">" + "无法找到种子");
                }
                return code;
            //}
        }

        #endregion

        #region 转换为MD5字符串 add by dufei
        public static string GetMD5String(string s)
        {
            string result = string.Empty;
            if (string.IsNullOrEmpty(s))
            {
                return result;
            }
            else
            {
                byte[] bt = Encoding.Default.GetBytes(s);
                MD5 md5 = new MD5CryptoServiceProvider();
                byte[] output = md5.ComputeHash(bt);
                result = BitConverter.ToString(output);
                return result;
            }
        }
        #endregion

        //#region 服务调用密码 add by dufei
        //public static string WebServicePwdGet(DataAccess.DataContext dc)
        //{
        //    var pwd = dc.DictionaryConfigs.Where(x => x.DataCode == "WebServicePwd").FirstOrDefault();
        //    if (pwd != null)
        //    {
        //        return pwd.DataValue.ToString();
        //    }
        //    else
        //    {
        //        return string.Empty;
        //    }
        //}
        //#endregion

        #region 取得大写金额
        public static string GetCapitalMoney(decimal? money)
        {
            if (money != null)
            {
                string s = money.Value.ToString("#L#E#D#C#K#E#D#C#J#E#D#C#I#E#D#C#H#E#D#C#G#E#D#C#F#E#D#C#.0B0A");
                string d = Regex.Replace(s, @"((?<=-|^)[^1-9]*)|((?'z'0)[0A-E]*((?=[1-9])|(?'-z'(?=[F-L\.]|$))))|((?'b'[F-L])(?'z'0)[0A-L]*((?=[1-9])|(?'-z'(?=[\.]|$))))", "${b}${z}");
                return Regex.Replace(d, ".", delegate(Match m) { return "负元空零壹贰叁肆伍陆柒捌玖空空空空空空空分角拾佰仟萬億兆京垓秭穰"[m.Value[0] - '-'].ToString(); });
            }
            else
            {
                return string.Empty;
            }
        }
        #endregion

        #region 通过密钥将内容加密
        // <summary>
        /// 通过密钥将内容加密
        /// </summary>
        /// <param name="stringToEncrypt"></param>
        /// <returns></returns>
        public static string EncryptString(string stringToEncrypt)
        {
            if (string.IsNullOrEmpty(stringToEncrypt))
            {
                return "";
            }

            string stringEncrypted = string.Empty;
            byte[] bytIn = System.Text.ASCIIEncoding.ASCII.GetBytes(stringToEncrypt);
            MemoryStream encryptStream = new System.IO.MemoryStream();
            CryptoStream encStream = new CryptoStream(encryptStream, GenerateDESCryptoServiceProvider().CreateEncryptor(), CryptoStreamMode.Write);

            try
            {
                encStream.Write(bytIn, 0, bytIn.Length);
                encStream.FlushFinalBlock();
                stringEncrypted = Convert.ToBase64String(encryptStream.ToArray(), 0, (int)encryptStream.Length);
            }
            catch
            {
                return "";
            }
            finally
            {
                encryptStream.Close();
                encStream.Close();
            }

            return stringEncrypted;
        }
        #endregion

        #region 通过密钥讲内容解密
        /// <summary>
        /// 通过密钥讲内容解密
        /// </summary>
        /// <param name="stringToDecrypt"></param>
        /// <returns></returns>
        public static string DecryptString(string stringToDecrypt)
        {
            if (String.IsNullOrEmpty(stringToDecrypt))
            {
                return "";
            }

            string stringDecrypted = string.Empty;
            byte[] bytIn = Convert.FromBase64String(stringToDecrypt.Replace(" ", "+"));
            MemoryStream decryptStream = new MemoryStream();
            CryptoStream encStream = new CryptoStream(decryptStream, GenerateDESCryptoServiceProvider().CreateDecryptor(), CryptoStreamMode.Write);

            try
            {
                encStream.Write(bytIn, 0, bytIn.Length);
                encStream.FlushFinalBlock();
                stringDecrypted = Encoding.Default.GetString(decryptStream.ToArray());
            }
            catch
            {
                return "";
            }
            finally
            {
                decryptStream.Close();
                encStream.Close();
            }

            return stringDecrypted;
        }

        private static DESCryptoServiceProvider GenerateDESCryptoServiceProvider()
        {
            DESCryptoServiceProvider dCrypter = new DESCryptoServiceProvider();
            string Key = System.Configuration.ConfigurationManager.AppSettings["Encryptionkey"].ToString();

            string sTemp;
            if (dCrypter.LegalKeySizes.Length > 0)
            {
                int moreSize = dCrypter.LegalKeySizes[0].MinSize;
                while (Key.Length > 7)
                {
                    Key = Key.Substring(0, 7);
                }
                sTemp = Key.PadRight(moreSize / 8, ' ');
            }
            else
            {
                sTemp = Key;
            }
            byte[] bytKey = ASCIIEncoding.ASCII.GetBytes(sTemp);

            dCrypter.Key = bytKey;
            dCrypter.IV = bytKey;

            return dCrypter;
        }

        #endregion

        #region 改变列表背景颜色
        public static System.Drawing.Color SetFullRowBgColor(bool flag)
        {
            if (flag)
            {
                return System.Drawing.Color.Pink;
            }
            else
            {
                return System.Drawing.Color.Empty;
            }
        }
        #endregion 改变列表背景颜色
    }
}
